package com.goldcn.template.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

public class GeneratorCode {

    //模板路径
    private static final String TEMPLATE_PATH = "src/main/resources/templates/";

    public static void generator(Map<String, Object> dataMap, String fileName, String templateName, String classPath) {
        // step1 创建freeMarker配置实例
        Configuration configuration = new Configuration(Configuration.getVersion());
        Writer out = null;
        try {
            // step2 获取模版路径
            configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));

            // step4 加载模版文件
            Template template = configuration.getTemplate(templateName);

            // step5 生成数据
            File packagePath = new File(classPath);
            if (!packagePath.exists()) {
                packagePath.mkdirs();
            }
            File docFile = new File(classPath + "\\" + fileName);

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            // step6 输出文件
            template.process(dataMap, out);

            System.out.println(fileName + "文件创建成功 !");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

}
